package com.chang.bootplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.EvaulateMap;
import com.chang.bootplus.controller.execl.DemoData;
import com.chang.bootplus.entity.StuTest;
import com.chang.bootplus.entity.Student;
import com.chang.bootplus.entity.WxUser;
import com.chang.bootplus.mapper.StudentMapper;
import com.chang.bootplus.po.CheckStatusPO;
import com.chang.bootplus.po.StudentForTimeStuIdPO;
import com.chang.bootplus.service.StuTestService;
import com.chang.bootplus.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.bootplus.service.WxUserService;
import com.chang.bootplus.vo.SchoolTestTimeVO;
import com.chang.bootplus.vo.StudentTimesVO;
import com.chang.bootplus.vo.TopMessageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chang
 * @since 2022-01-23
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class
StudentServiceImp extends ServiceImpl<StudentMapper, Student> implements StudentService {

    final WxUserService wxUserService;

    final StuTestService stuTestService;

    @Override
    public ApiResponse<TopMessageVO> topMessage(CheckStatusPO po) {
        WxUser one = wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId, po.getOpenId()));
        if(po.getOpenId() == null || one == null){
            throw new BusException("未登录");
        }

        Student student = getOne(new LambdaQueryWrapper<Student>().eq(Student::getOpenId, po.getOpenId()));
        if(student == null || student.getOpenId().equals("0")){
            throw new BusException("未绑定");
        }

        TopMessageVO topMessageVO = new TopMessageVO();
        String[] mapGrade = {"一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三","大一","大二","大三","大四"};
        Map<String,String> mapClass = new HashMap<>();
        String[] mapNation = {"汉族",
                "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族", "满族", "侗族", "瑶族", "白族", "土家族",
                "哈尼族", "哈萨克族", "傣族", "黎族", "僳僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族",
                "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "塔吉克族",
                "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族",
                "赫哲族", "门巴族", "珞巴族", "基诺族", "其他", "外国血统"
        };
        int keyClassId = 101;
        for(int i=0;i<58;i++){
            keyClassId+=i;
            String tempId = "0"+keyClassId;
            String tempClassName = (i+1) + "班";
            mapClass.put(tempId,tempClassName);
        }

        int gradeId = Integer.parseInt(student.getGradeId());
        String classId = student.getClassId();
//        int nationId = Integer.parseInt(student.getNationId());

        topMessageVO.setGradeOfStudent(mapGrade[gradeId - 11]).setClassOfStudent(mapClass.get(classId)).setScoreSum(student.getScore()).setImgUrl(one.getImageUrl());
        return new ApiResponse<>(topMessageVO);

    }

    @Override
    public ApiResponse<StudentTimesVO> testStudentTimeDisplay(StudentForTimeStuIdPO po) {
        List<StuTest> list = stuTestService.list(new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId, po.getStuId()));
        if(list == null || list.size() == 0){
            throw new BusException("没有找到该学号对应的学生测试成绩");
        }

        List<String> listRes = list.stream().map(stuTest -> stuTest.getGmtCreate().toString().substring(0, 10)).collect(Collectors.toList());

        listRes.sort((o1, o2) -> {
            String[] split1 = o1.split("-");
            String[] split2 = o2.split("-");

            Integer y1 = Integer.parseInt(split1[0].replaceAll("^(0+)", ""));
            Integer y2 = Integer.parseInt(split2[0].replaceAll("^(0+)", ""));
            Integer m1 = Integer.parseInt(split1[1].replaceAll("^(0+)", ""));
            Integer m2 = Integer.parseInt(split2[1].replaceAll("^(0+)", ""));
            Integer d1 = Integer.parseInt(split1[2].replaceAll("^(0+)", ""));
            Integer d2 = Integer.parseInt(split2[2].replaceAll("^(0+)", ""));

            if(y1.equals(y2)){
                if(m1.equals(m2)){
                    return d2-d1;
                }
                return m2 - m1;
            }

            return y2 - y1;
        });
        StudentTimesVO studentTimesVO = new StudentTimesVO();
        studentTimesVO.setTestTimes(listRes);
        return new ApiResponse<>(studentTimesVO);
    }

    @Transactional
    @Override
    public void saveExcel(List<DemoData> list,String schoolName,LocalDateTime parse) {
        // 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入
        LinkedList<Student> studentsList = new LinkedList<>();
        LinkedList<StuTest> stuTestsList = new LinkedList<>();
//        try {
            list.stream().forEach(t->{
                String classId1 = t.getClassId();
                if(classId1!=null&&classId1.length()!=6){
                    throw new BusException("你不能导入学号为 "+classId1.length()+" 位的学号");
                }
                Student student = BeanUtil.beanA2beanB(t, Student.class);
                Double bmi=null;
                if (student.getWeight()!=null&&student.getHeight()!=null){
                    bmi=(student.getWeight())/(student.getHeight()*0.01)/(student.getHeight()*0.01);
                    String format = String.format("%.1f", bmi);// 保留一位小数
                    bmi= new Double(format);
                }
                student.setBmi(bmi);
                System.out.println(student);
                if (student.getStuId()==null){
                    return;
                }

                Integer classId  = new Integer(t.getGradeId().substring(1));
                if (t.getSex()==null) throw new BusException("导入的数据中存在性别为空");
                Integer sex  = new Integer(t.getSex());
                sex= sex == 2 ? 0 : 1;
                StuTest stuTest = new StuTest();
                EvaulateMap evaulateMap = new EvaulateMap();
                Integer score1 = t.getTestFifty()==null?null:evaulateMap.calculateAll(classId, sex, 2, t.getTestFifty()).getScore();
                System.out.println(" 50米----》"+score1);
                Integer score1bmi =bmi==null?null: evaulateMap.calculateAll(classId, sex, 7, bmi).getScore();
                Integer score2 = t.getVital()==null?null:evaulateMap.calculateAll(classId,sex,1,t.getVital().doubleValue()).getScore();
                Integer score3 = t.getTestSitRech()==null?null:evaulateMap.calculateAll(classId,sex,3,t.getTestSitRech()).getScore();
                Integer score4 = t.getTestSkip()==null?null:evaulateMap.calculateAll(classId,sex,4,t.getTestSkip().doubleValue()).getScore();
                Integer score5 = t.getTestSitup()==null?null:evaulateMap.calculateAll(classId,sex,5,t.getTestSitup().doubleValue()).getScore();
                Integer score6 = t.getTestRun()==null?null:evaulateMap.calculateAll(classId,sex,6,t.getTestRun()).getScore();
                Integer score44=null;
                if (score4==null){
                    score44=null;
                } else {
                    score44=score4> 100 ? 100 :score4;
                }
                Integer otherScore = evaulateMap.getOtherScore()==null ? 0:evaulateMap.getOtherScore();
                stuTest.setStuId(t.getStuId())
                        .setBmi(score1bmi)
                        .setTestFifty(score1)
                        .setVital(score2)
                        .setTestSitRech(score3)
                        .setTestSkip(score44)
                        .setTestSitup(score5)
                        .setTestRun(score6)
                        .setResultOther(evaulateMap.getOtherScore())
                        .setSchoolName(schoolName)
                        .setScore(EvaulateMap.getAllScore2(score1,score1bmi,score2,score5,score4,score6,score3,classId)==null? null:EvaulateMap.getAllScore2(score1,score1bmi,score2,score5,score4,score6,score3,classId));
                stuTest.setGmtCreate(parse);
                stuTestsList.add(stuTest);
//                stuTestService.save(stuTest);
                student.setSex(sex);
                student.setResultOther(evaulateMap.getOtherScore());
                student.setScore(EvaulateMap.getAllScore2(score1,score1bmi,score2,score5,score4,score6,score3,classId)==null? null:EvaulateMap.getAllScore2(score1,score1bmi,score2,score5,score4,score6,score3,classId).intValue());
                student.setSchoolName(schoolName);
                student.setGmtCreate(parse);
                save(student);
                studentsList.add(student);
            });
//            saveOrUpdateBatch(studentsList);
            stuTestService.saveBatch(stuTestsList);

//        }catch (Exception e){
//            throw new BusException("导入失败");
//        }
    }




}
